package com.getpebble.android.framework.notification.gmail;

import android.accounts.Account;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.common.core.async.PblAsyncTask;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.ObjectUtil;
import com.getpebble.android.common.core.util.PblPreferences;
import com.getpebble.android.common.core.util.PblPreferences.PrefKey;
import com.getpebble.android.common.model.PblNotificationModel.Record;
import com.getpebble.android.framework.notification.PblNotificationProcessor;
import com.getpebble.android.framework.notification.PblNotificationProcessor.InvokeActionResult;
import com.getpebble.android.framework.receiver.GmailReceiver;
import com.getpebble.android.notifications.model.PblNotification;
import com.getpebble.android.notifications.model.PblNotification.LegacyNotification;
import com.getpebble.android.notifications.model.PblNotification.NotificationContent;
import com.getpebble.android.notifications.model.PblNotification.Source;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.smtp.SMTPMessage;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;
import javax.mail.Address;
import javax.mail.AuthenticationFailedException;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Flags.Flag;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeUtility;
import javax.mail.search.AndTerm;
import javax.mail.search.FlagTerm;
import javax.mail.search.SubjectTerm;
import org.apache.commons.io.output.NullOutputStream;

public class GmailCheckerService extends IntentService {
    public static final String EXTRA_ACCOUNT = "account";
    public static final String EXTRA_COUNT = "count";
    private static final String FOLDER_INBOX = "INBOX";
    private static final int NUM_MESSAGES_TO_CHECK_FOR_ACTION = 20;
    private static final String TAG = GmailCheckerService.class.getSimpleName();
    public static final Pattern USELESS_TAGS_PATTERN = Pattern.compile("<head[^>]*>.*?</head>|<style[^>]*>.*?</style>", 34);
    private static final Map<String, String> sAuthTokens = new HashMap();
    private PblPreferences mPreferences;

    public interface ActionCallback {
        void result(InvokeActionResult invokeActionResult);

        void setNotificationRecord(Record record);
    }

    static /* synthetic */ class AnonymousClass2 {
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$notification$gmail$GmailCheckerService$GmailAction = new int[GmailAction.values().length];

        static {
            try {
                $SwitchMap$com$getpebble$android$framework$notification$gmail$GmailCheckerService$GmailAction[GmailAction.MARK_AS_READ.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$notification$gmail$GmailCheckerService$GmailAction[GmailAction.STAR_AND_MARK_READ.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
        }
    }

    private static class EmailNotification {
        public final String body;
        public final String from;
        public final String subject;

        private EmailNotification(String from, String subject, String body) {
            this.from = from;
            this.subject = subject;
            this.body = body;
        }
    }

    public enum GmailAction {
        MARK_AS_READ,
        STAR_AND_MARK_READ
    }

    private static class GmailActionTask extends PblAsyncTask {
        final String mAccount;
        final GmailAction mAction;
        final ActionCallback mCallback;
        final MessageId mMessageId;

        private GmailActionTask(String account, GmailAction action, MessageId messageId, ActionCallback callback) {
            this.mAccount = account;
            this.mAction = action;
            this.mMessageId = messageId;
            this.mCallback = callback;
        }

        public boolean doInBackground() {
            Trace.verbose(TAG, "performMessageAction account = " + this.mAccount + " action = " + this.mAction);
            Store store = null;
            IMAPFolder folder = null;
            try {
                String credential = Gmail.getGmailTokenFromBackground(PebbleApplication.getAppContext(), this.mAccount);
                if (credential == null) {
                    Trace.debug(TAG, "Could not get token for " + this.mAccount);
                    if (folder != null) {
                        try {
                            folder.close(false);
                        } catch (IllegalStateException e) {
                            Trace.warning(TAG, "Tried to close an already closed folder");
                        }
                    }
                    if (store == null) {
                        return false;
                    }
                    try {
                        store.close();
                        return false;
                    } catch (Exception e2) {
                        Trace.warning(TAG, "Failed to clean up IMAP connection", e2);
                        return false;
                    }
                } else if (TextUtils.isEmpty(credential)) {
                    Trace.info(TAG, "Didn't get token; waiting for accept for account: " + this.mAccount);
                    if (folder != null) {
                        try {
                            folder.close(false);
                        } catch (IllegalStateException e3) {
                            Trace.warning(TAG, "Tried to close an already closed folder");
                        }
                    }
                    if (store == null) {
                        return false;
                    }
                    try {
                        store.close();
                        return false;
                    } catch (Exception e22) {
                        Trace.warning(TAG, "Failed to clean up IMAP connection", e22);
                        return false;
                    }
                } else {
                    store = Gmail.getStoreForAccount(this.mAccount, credential);
                    if (store == null) {
                        Trace.warning(TAG, "store is null");
                        if (folder != null) {
                            try {
                                folder.close(false);
                            } catch (IllegalStateException e4) {
                                Trace.warning(TAG, "Tried to close an already closed folder");
                            }
                        }
                        if (store == null) {
                            return false;
                        }
                        try {
                            store.close();
                            return false;
                        } catch (Exception e222) {
                            Trace.warning(TAG, "Failed to clean up IMAP connection", e222);
                            return false;
                        }
                    }
                    folder = (IMAPFolder) store.getFolder(GmailCheckerService.FOLDER_INBOX);
                    folder.open(2);
                    long start = System.currentTimeMillis();
                    Message message = GmailCheckerService.findMessage(folder, this.mMessageId);
                    Trace.verbose(TAG, "Took " + (System.currentTimeMillis() - start) + " ms to find message");
                    if (message == null) {
                        Trace.debug(TAG, "Message not found");
                        if (folder != null) {
                            try {
                                folder.close(false);
                            } catch (IllegalStateException e5) {
                                Trace.warning(TAG, "Tried to close an already closed folder");
                            }
                        }
                        if (store == null) {
                            return false;
                        }
                        try {
                            store.close();
                            return false;
                        } catch (Exception e2222) {
                            Trace.warning(TAG, "Failed to clean up IMAP connection", e2222);
                            return false;
                        }
                    }
                    switch (AnonymousClass2.$SwitchMap$com$getpebble$android$framework$notification$gmail$GmailCheckerService$GmailAction[this.mAction.ordinal()]) {
                        case SMTPMessage.RETURN_FULL /*1*/:
                            message.setFlag(Flag.SEEN, true);
                            if (folder != null) {
                                try {
                                    folder.close(false);
                                } catch (IllegalStateException e6) {
                                    Trace.warning(TAG, "Tried to close an already closed folder");
                                }
                            }
                            if (store == null) {
                                return true;
                            }
                            try {
                                store.close();
                                return true;
                            } catch (Exception e22222) {
                                Trace.warning(TAG, "Failed to clean up IMAP connection", e22222);
                                return true;
                            }
                        case SMTPMessage.RETURN_HDRS /*2*/:
                            message.setFlag(Flag.FLAGGED, true);
                            message.setFlag(Flag.SEEN, true);
                            if (folder != null) {
                                try {
                                    folder.close(false);
                                } catch (IllegalStateException e7) {
                                    Trace.warning(TAG, "Tried to close an already closed folder");
                                }
                            }
                            if (store == null) {
                                return true;
                            }
                            try {
                                store.close();
                                return true;
                            } catch (Exception e222222) {
                                Trace.warning(TAG, "Failed to clean up IMAP connection", e222222);
                                return true;
                            }
                        default:
                            if (folder != null) {
                                try {
                                    folder.close(false);
                                } catch (IllegalStateException e8) {
                                    Trace.warning(TAG, "Tried to close an already closed folder");
                                }
                            }
                            if (store != null) {
                                try {
                                    store.close();
                                    break;
                                } catch (Exception e2222222) {
                                    Trace.warning(TAG, "Failed to clean up IMAP connection", e2222222);
                                    break;
                                }
                            }
                            break;
                    }
                    return false;
                }
            } catch (AuthenticationFailedException auth) {
                Trace.warning(TAG, "Failed to retrieve new Gmail message: bad credentials: ", auth);
                if (folder != null) {
                    try {
                        folder.close(false);
                    } catch (IllegalStateException e9) {
                        Trace.warning(TAG, "Tried to close an already closed folder");
                    }
                }
                if (store != null) {
                    try {
                        store.close();
                    } catch (Exception e22222222) {
                        Trace.warning(TAG, "Failed to clean up IMAP connection", e22222222);
                    }
                }
            } catch (MessagingException me) {
                Trace.warning(TAG, "Failed to retrieve new Gmail message", me);
                if (folder != null) {
                    try {
                        folder.close(false);
                    } catch (IllegalStateException e10) {
                        Trace.warning(TAG, "Tried to close an already closed folder");
                    }
                }
                if (store != null) {
                    try {
                        store.close();
                    } catch (Exception e222222222) {
                        Trace.warning(TAG, "Failed to clean up IMAP connection", e222222222);
                    }
                }
            } catch (Exception e2222222222) {
                Trace.error(TAG, "Failed to retrieve new Gmail message", e2222222222);
                if (folder != null) {
                    try {
                        folder.close(false);
                    } catch (IllegalStateException e11) {
                        Trace.warning(TAG, "Tried to close an already closed folder");
                    }
                }
                if (store != null) {
                    try {
                        store.close();
                    } catch (Exception e22222222222) {
                        Trace.warning(TAG, "Failed to clean up IMAP connection", e22222222222);
                    }
                }
            } catch (Throwable th) {
                if (folder != null) {
                    try {
                        folder.close(false);
                    } catch (IllegalStateException e12) {
                        Trace.warning(TAG, "Tried to close an already closed folder");
                    }
                }
                if (store != null) {
                    try {
                        store.close();
                    } catch (Exception e222222222222) {
                        Trace.warning(TAG, "Failed to clean up IMAP connection", e222222222222);
                    }
                }
            }
        }

        public void onTaskSuccess() {
            this.mCallback.result(InvokeActionResult.DEFAULT_ACTION);
        }

        public void onTaskFailed() {
            this.mCallback.result(InvokeActionResult.FAILED);
        }
    }

    public static class MessageId {
        private static final String TRUNCATED_TAG_PREFIX = "\u2026]";
        private final String mProcessedTitle = preprocessString(this.mTitle);
        private final String mSender;
        private final long mTimestampSeconds;
        private final String mTitle;

        private MessageId(long timestampMillis, String title, String sender) {
            this.mTimestampSeconds = timestampMillis / 1000;
            this.mTitle = title;
            this.mSender = sender;
        }

        public static MessageId from(Message message) throws MessagingException {
            String sender = null;
            if (message.getFrom().length > 0) {
                sender = GmailCheckerService.formatSenderAddress(message.getFrom()[0].toString());
            }
            return new MessageId(message.getReceivedDate().getTime(), message.getSubject(), sender);
        }

        public static MessageId from(PblNotification notification) throws IllegalArgumentException {
            String subject = "";
            NotificationContent content = notification.getNotificationContent();
            if (content == null) {
                throw new IllegalArgumentException("content is null");
            } else if (content.notificationBody == null) {
                throw new IllegalArgumentException("notificationBody is null");
            } else if (content.notificationTitle == null) {
                throw new IllegalArgumentException("notificationTitle is null");
            } else {
                String[] lines = content.notificationBody.split(System.getProperty("line.separator"));
                if (lines.length > 0) {
                    subject = lines[0];
                }
                return new MessageId(notification.getNotification().when, subject, notification.getNotificationContent().notificationTitle);
            }
        }

        public boolean matches(MessageId other) {
            Trace.verbose(GmailCheckerService.TAG, "Comparing " + this + " to " + other);
            if (this.mProcessedTitle == null || other.mTitle == null || !other.mTitle.contains(this.mProcessedTitle) || !ObjectUtil.nullCheckEquals(this.mSender, other.mSender)) {
                return false;
            }
            Trace.verbose(GmailCheckerService.TAG, "... matches!!");
            return true;
        }

        public String toString() {
            return "<timestampSeconds: " + this.mTimestampSeconds + " title: '" + this.mTitle + "' sender: '" + this.mSender + "'";
        }

        static String preprocessString(String title) {
            if (title == null) {
                return null;
            }
            String working = title;
            if (!working.contains(TRUNCATED_TAG_PREFIX)) {
                return working;
            }
            int pos = working.indexOf(TRUNCATED_TAG_PREFIX);
            if (pos <= -1) {
                return working;
            }
            int afterTagPos = pos + TRUNCATED_TAG_PREFIX.length();
            if (afterTagPos < working.length()) {
                return working.substring(afterTagPos);
            }
            return working;
        }
    }

    static {
        System.setProperty("mail.mime.decodetext.strict", "false");
    }

    public GmailCheckerService() {
        super("GmailCheckerService");
    }

    protected void onHandleIntent(Intent intent) {
        Context context = getApplicationContext();
        if (context == null) {
            Trace.error(TAG, "onHandleIntent: context was null");
            return;
        }
        this.mPreferences = new PblPreferences(context);
        String account = intent.getStringExtra(EXTRA_ACCOUNT);
        int count = intent.getIntExtra(EXTRA_COUNT, 0);
        Store store = null;
        IMAPFolder fldr = null;
        List<EmailNotification> messagesToNotify = new LinkedList();
        try {
            Session session = Session.getInstance(new Properties());
            session.setDebug(false);
            session.setDebugOut(new PrintStream(new NullOutputStream()));
            String credential = Gmail.getGmailTokenFromBackground(this, account, GmailReceiver.buildUpdateIntent(account, count));
            if (TextUtils.isEmpty(credential)) {
                Trace.info(TAG, "Didn't get token; waiting for accept for account: " + account);
                if (fldr != null) {
                    try {
                        fldr.close(false);
                    } catch (IllegalStateException e) {
                        Trace.warning(TAG, "Tried to close an already closed folder");
                    }
                }
                if (store != null) {
                    try {
                        store.close();
                        return;
                    } catch (Exception e2) {
                        Trace.warning(TAG, "Failed to clean up IMAP connection", e2);
                        return;
                    }
                }
                return;
            }
            store = Gmail.getStoreForAccount(account, credential);
            if (store == null) {
                Trace.warning(TAG, "store is null");
                if (fldr != null) {
                    try {
                        fldr.close(false);
                    } catch (IllegalStateException e3) {
                        Trace.warning(TAG, "Tried to close an already closed folder");
                    }
                }
                if (store != null) {
                    try {
                        store.close();
                        return;
                    } catch (Exception e22) {
                        Trace.warning(TAG, "Failed to clean up IMAP connection", e22);
                        return;
                    }
                }
                return;
            }
            fldr = (IMAPFolder) store.getFolder(FOLDER_INBOX);
            fldr.open(1);
            Trace.verbose(TAG, "Connected to INBOX");
            messagesToNotify.addAll(fetchNewEmails(fldr, count, account));
            if (fldr != null) {
                try {
                    fldr.close(false);
                } catch (IllegalStateException e4) {
                    Trace.warning(TAG, "Tried to close an already closed folder");
                }
            }
            if (store != null) {
                try {
                    store.close();
                } catch (Exception e222) {
                    Trace.warning(TAG, "Failed to clean up IMAP connection", e222);
                }
            }
            Trace.verbose(TAG, String.format("%d messages to notify", new Object[]{Integer.valueOf(messagesToNotify.size())}));
            if (messagesToNotify.size() > 0) {
                Collections.reverse(messagesToNotify.subList(0, Math.min(messagesToNotify.size(), 10)));
                for (EmailNotification message : messagesToNotify) {
                    sendNotificationToWatch(message.from, message.subject, message.body);
                }
            }
        } catch (AuthenticationFailedException auth) {
            Trace.warning(TAG, "Failed to retrieve new Gmail messages: bad credentials: ", auth);
            Gmail.getGmailTokenFromBackground(this, account, GmailReceiver.buildUpdateIntent(account, count));
            if (fldr != null) {
                try {
                    fldr.close(false);
                } catch (IllegalStateException e5) {
                    Trace.warning(TAG, "Tried to close an already closed folder");
                }
            }
            if (store != null) {
                try {
                    store.close();
                } catch (Exception e2222) {
                    Trace.warning(TAG, "Failed to clean up IMAP connection", e2222);
                }
            }
        } catch (MessagingException me) {
            Trace.warning(TAG, "Failed to retrieve new Gmail messages", me);
            if (fldr != null) {
                try {
                    fldr.close(false);
                } catch (IllegalStateException e6) {
                    Trace.warning(TAG, "Tried to close an already closed folder");
                }
            }
            if (store != null) {
                try {
                    store.close();
                } catch (Exception e22222) {
                    Trace.warning(TAG, "Failed to clean up IMAP connection", e22222);
                }
            }
        } catch (Exception e222222) {
            Trace.error(TAG, "Failed to retrieve new Gmail messages", e222222);
            if (fldr != null) {
                try {
                    fldr.close(false);
                } catch (IllegalStateException e7) {
                    Trace.warning(TAG, "Tried to close an already closed folder");
                }
            }
            if (store != null) {
                try {
                    store.close();
                } catch (Exception e2222222) {
                    Trace.warning(TAG, "Failed to clean up IMAP connection", e2222222);
                }
            }
        } catch (Throwable th) {
            if (fldr != null) {
                try {
                    fldr.close(false);
                } catch (IllegalStateException e8) {
                    Trace.warning(TAG, "Tried to close an already closed folder");
                }
            }
            if (store != null) {
                try {
                    store.close();
                } catch (Exception e22222222) {
                    Trace.warning(TAG, "Failed to clean up IMAP connection", e22222222);
                }
            }
        }
    }

    private List<EmailNotification> fetchNewEmails(IMAPFolder fldr, int newMessages, String account) throws MessagingException, RuntimeException {
        List<EmailNotification> messagesToNotify = new LinkedList();
        boolean isGmailEnabledForAccount = this.mPreferences.getSharedPreferences().getBoolean(this.mPreferences.prefKeyToString(PrefKey.GMAIL_ACCOUNT_ENABLED_PREFIX) + account, false);
        if (newMessages > 0 && isGmailEnabledForAccount) {
            String gmailAccountUidPreferenceKey = this.mPreferences.prefKeyToString(PrefKey.GMAIL_ACCOUNT_UID_PREFIX) + account;
            long lastUid = this.mPreferences.getSharedPreferences().getLong(gmailAccountUidPreferenceKey, 0);
            long newLastUid = lastUid;
            int messageNumber = fldr.getMessageCount();
            int unseenMessagesProcessed = 0;
            while (messageNumber >= 0 && unseenMessagesProcessed < newMessages) {
                try {
                    Message m = fldr.getMessage(messageNumber);
                    long messageUid = fldr.getUID(m);
                    Trace.debug(TAG, "processing message with UID = " + messageUid + " number = " + m.getMessageNumber());
                    if (messageUid > newLastUid) {
                        newLastUid = messageUid;
                        this.mPreferences.getSharedPreferences().edit().putLong(gmailAccountUidPreferenceKey, newLastUid).apply();
                    }
                    if (messageUid <= lastUid) {
                        Trace.debug(TAG, "Message " + messageUid + " UID from past; stopping");
                        break;
                    }
                    if (m.getFlags().contains(Flag.SEEN)) {
                        Trace.debug(TAG, "Message " + messageUid + " has SEEN flag set; continuing");
                    } else {
                        unseenMessagesProcessed++;
                        EmailNotification email = slurpMessage(m);
                        if (email != null) {
                            messagesToNotify.add(email);
                            Trace.verbose(TAG, "Message " + fldr.getUID(m) + " scheduled for notification");
                        }
                    }
                    messageNumber--;
                } catch (IndexOutOfBoundsException ioobe) {
                    Trace.warning(TAG, String.format("messageNumber '%d' is invalid", new Object[]{Integer.valueOf(messageNumber)}), ioobe);
                }
            }
        }
        return messagesToNotify;
    }

    private EmailNotification slurpMessage(Message m) throws MessagingException {
        try {
            Address[] from = m.getFrom();
            String subject = m.getSubject();
            Object contentObject = m.getContent();
            String contentType = m.getContentType();
            String body = "";
            ArrayList<String> attachments = new ArrayList();
            if (contentObject instanceof String) {
                body = contentObject.toString();
            } else if (contentObject instanceof Multipart) {
                BodyPart b = findBodyContent((Multipart) contentObject, attachments, new String[]{"text/plain", "text/html"});
                if (b != null) {
                    try {
                        body = convertHtmlToText(b.getContent().toString());
                    } catch (RuntimeException re) {
                        Trace.warning(TAG, "Failed to convert message to plain-text; continuing", re.getCause());
                    }
                    contentType = b.getContentType();
                }
            } else {
                Trace.warning(TAG, "Failed to identify type of message content.");
                Trace.warning(TAG, "ContentType: " + m.getContentType());
            }
            Trace.verbose(TAG, "Content type: " + contentType);
            if (contentType.toLowerCase().contains("html")) {
                Trace.verbose(TAG, "Content in HTML.");
                body = convertHtmlToText(body);
            }
            if (body == null && subject == null) {
                return null;
            }
            String formattedSenderAddr;
            if (from.length > 0) {
                formattedSenderAddr = formatSenderAddress(from[0].toString());
            } else {
                formattedSenderAddr = "unknown";
            }
            if (body == null) {
                body = "";
            }
            if (subject == null) {
                subject = "";
            }
            return new EmailNotification(formattedSenderAddr, decodeText(subject), body);
        } catch (IOException ioe) {
            Trace.warning(TAG, "Could not retrieve message body; skipping", ioe);
            return null;
        }
    }

    private static String decodeText(String s) {
        try {
            return MimeUtility.decodeText(s);
        } catch (UnsupportedEncodingException e) {
            Trace.debug(TAG, "Could not decode sender addresss", e);
            return s;
        }
    }

    static String formatSenderAddress(String sender) {
        String formattedSenderAddr = decodeText(sender);
        int angleBracketIndex = formattedSenderAddr.indexOf("<");
        if (angleBracketIndex > 0) {
            formattedSenderAddr = formattedSenderAddr.substring(0, angleBracketIndex).trim();
        } else if (angleBracketIndex == 0) {
            formattedSenderAddr = formattedSenderAddr.substring(1, formattedSenderAddr.length() - 1);
        }
        if (formattedSenderAddr.length() > 2 && formattedSenderAddr.charAt(0) == '\"' && formattedSenderAddr.charAt(formattedSenderAddr.length() - 1) == '\"') {
            return formattedSenderAddr.substring(1, formattedSenderAddr.length() - 1);
        }
        return formattedSenderAddr;
    }

    private void sendNotificationToWatch(String fromAddress, String subject, String body) {
        LegacyNotification content = new LegacyNotification();
        content.title = fromAddress;
        content.body = subject + "\n" + body;
        PblNotificationProcessor.processNotification(PblNotification.from(content, Source.GMAIL));
    }

    private BodyPart findBodyContent(Multipart p, ArrayList<String> attachments, String[] mimeTypes) throws MessagingException, IOException {
        BodyPart bodyPart = null;
        for (int i = 0; i < p.getCount(); i++) {
            BodyPart b = p.getBodyPart(i);
            String partType = b.getContentType().toLowerCase();
            if (b.getFileName() != null) {
                attachments.add(b.getFileName());
            }
            for (String type : mimeTypes) {
                if (partType.contains(type) && (bodyPart == null || !bodyPart.getContentType().toLowerCase().contains(mimeTypes[0]))) {
                    bodyPart = b;
                }
            }
            if (partType.contains("multipart/")) {
                bodyPart = findBodyContent((Multipart) b.getContent(), attachments, mimeTypes);
            }
        }
        return bodyPart;
    }

    String convertHtmlToText(String body) {
        try {
            return Html.fromHtml(USELESS_TAGS_PATTERN.matcher(body).replaceFirst("")).toString().trim();
        } catch (RuntimeException re) {
            if (re.getCause() instanceof IOException) {
                Trace.warning(TAG, "Failed to convert message to plain-text", re.getCause());
                return null;
            }
            throw re;
        }
    }

    private static Message findMessage(IMAPFolder folder, MessageId messageId) throws MessagingException {
        Message[] foundMessages = folder.search(new AndTerm(new FlagTerm(new Flags(Flag.SEEN), false), new SubjectTerm(messageId.mProcessedTitle)));
        if (foundMessages == null) {
            Trace.debug(TAG, "foundMessages is null");
            return null;
        }
        for (Message unreadMessage : foundMessages) {
            if (messageId.matches(MessageId.from(unreadMessage))) {
                return unreadMessage;
            }
        }
        return null;
    }

    public static void performMessageAction(String account, GmailAction action, MessageId messageId, ActionCallback callback) {
        new GmailActionTask(account, action, messageId, callback).submit();
    }

    public static String getToken(String account) {
        String str;
        synchronized (sAuthTokens) {
            str = (String) sAuthTokens.get(account);
        }
        return str;
    }

    public static void initGmailTokens() {
        new PblAsyncTask() {
            public boolean doInBackground() {
                Trace.debug(TAG, "initGmailTokens()");
                synchronized (GmailCheckerService.sAuthTokens) {
                    for (Account account : GmailAddress.getAccountsList(PebbleApplication.getAppContext())) {
                        Trace.verbose(TAG, "Getting token for " + account.name);
                        String token = Gmail.getGmailTokenFromBackground(PebbleApplication.getAppContext(), account.name);
                        if (token == null) {
                            Trace.debug(TAG, "Could not get token for " + account.name);
                        } else {
                            GmailCheckerService.sAuthTokens.put(account.name, token);
                        }
                    }
                }
                return true;
            }

            public void onTaskSuccess() {
            }

            public void onTaskFailed() {
            }
        }.submit();
    }
}
